import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth.js'
import { Promise } from 'core-js'

const state = {
  // 一进来优先从缓存中取
  token: getToken(), // token字符串,
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 设置了 token 的同时, 同步到本地cookies中
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  login(context, data) {
    return new Promise((resolve, reject) => {
      reqLogin(data).then(res => {
        const token = res.data
        context.commit('setToken', token)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  async getUserInfo(context) {
    const { data: data1 } = await reqGetUserInfo()
    const { data: data2 } = await reqGetUserDetailById(data1.userId)
    const baseResuit = {
      ... data1,
      ... data2
    }
    context.commit('setUserInfo', baseResuit)
    return baseResuit
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
